<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="行为标题" prop="behaviorTitle">
        <el-input
          v-model="queryParams.behaviorTitle"
          placeholder="请输入行为标题"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增配置</el-button
        >
      </el-col>
    </el-row>

    <el-table :data="dataList" v-loading="loading">
      <!-- <el-table-column type="selection" width="50" align="center" /> -->
      <el-table-column
        type="index"
        :index="table_index"
        label="序号"
        align="center"
      />
      <el-table-column prop="id" align="center" label="id" v-if="false" />
      <el-table-column prop="behaviorTitle" align="center" label="行为标题" />
      <el-table-column prop="scoreCycle" align="center" label="评分周期">
        <template slot-scope="scope">
          {{
            getLable(scoreCycleOption, scope.row.scoreCycle, "value", "lable")
          }}
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center" label="状态">
        <template slot-scope="scope">
          {{ scope.row.status == 0 ? "未使用" : "已使用" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            circle
            type="success"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          />
          <el-button
            size="mini"
            circle
            type="info"
            icon="el-icon-connection"
            @click="beforeCreateCfgClass(scope.row)"
          />
          <el-button
            v-if="scope.row.status === 0"
            size="mini"
            circle
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="title"
      :visible.sync="cfgDialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        :model="behaviorCfgForm"
        ref="behaviorCfgForm"
        :rules="rules"
        label-width="20px"
        v-loading="cfgDialogLoading"
      >
        <el-form-item label="配置id" prop="id" v-if="false">
          <el-input v-model="behaviorCfgForm.id"></el-input
        ></el-form-item>
        <el-form-item label="行为标题" prop="behaviorTitle" label-width="80px">
          <el-input
            style="width: 100%"
            v-model="behaviorCfgForm.behaviorTitle"
            placeholder="请输入"
            :disabled="isView"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="评分周期" prop="scoreCycle" label-width="80px">
          <el-select
            v-model="behaviorCfgForm.scoreCycle"
            clearable
            filterable
            placeholder="请选择"
            style="width: 100%"
            :disabled="isEdit"
          >
            <el-option
              v-for="item in scoreCycleOption"
              :key="item.value"
              :label="item.lable"
              :value="item.value"
            >
            </el-option
          ></el-select>
        </el-form-item>

        <el-form-item
          label="评分项"
          prop="behaviorCfgItemList"
          label-width="80px"
        >
          <el-table
            :data="behaviorCfgForm.behaviorCfgItemList"
            border
            style="width: 100%"
          >
            <el-table-column prop="markItem" label="名称">
              <template slot-scope="scope">
                <el-form-item
                  label=" "
                  :prop="'behaviorCfgItemList.' + scope.$index + '.markItem'"
                  :rules="{ required: true, message: '必填', trigger: 'blur' }"
                >
                  <el-input
                    v-model="scope.row.markItem"
                    autocomplete="off"
                    placeholder="请输入评分项名称"
                    :disabled="isEdit"
                  >
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  plain
                  @click="delRow(scope.$index, scope.row)"
                  :disabled="isEdit"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <i
            class="el-icon-circle-plus-outline"
            @click="addRow"
            v-show="isEdit == false"
          ></i>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">提 交</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="请选择应用此配置的班级"
      :visible.sync="cfgClassDialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-transfer
        v-model="cfgClass.classIdList"
        :titles="['未应用此配置班级', '应用此配置班级']"
        :props="{
          key: 'id',
          label: 'className',
        }"
        :data="classOption"
        @change="monitorTransferChange"
        v-loading="cfgClassDialogLoading"
      >
      </el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createCfgClass">提 交</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { findAllSchoolClass } from "@/api/classManage/classInfo";
import {
  findCfgPageList,
  createOrUpdateCfg,
  delCfg,
} from "@/api/studyManage/behaviorCfg";
import {
  createOrUpdateCfgClassBatch,
  findCfgClassByCfgId,
} from "@/api/studyManage/behaviorCfgClass";
import { findBehaviorCfgItemByCfgId } from "@/api/studyManage/behaviorCfgItem";

export default {
  name: "BehaviorConfig",
  data() {
    return {
      // 遮罩层
      loading: true,
      cfgDialogLoading: true,
      cfgClassDialogLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //控制弹窗是否弹出
      cfgDialogVisible: false,
      cfgClassDialogVisible: false,
      //防止重复提交
      transferMonitor: true,
      //控制是否可编辑
      isView: false,
      isEdit: false,
      //数据列表
      dataList: [],
      //班级选项
      classOption: [],
      //评分周期选项
      scoreCycleOption: [
        {
          value: 1,
          lable: "每天",
        },
        {
          value: 2,
          lable: "每周",
        },
        {
          value: 3,
          lable: "每月",
        },
        {
          value: 4,
          lable: "每年",
        },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        behaviorTitle: undefined,
      },
      behaviorCfgForm: {
        id: undefined,
        behaviorTitle: undefined,
        scoreCycle: undefined,
        behaviorCfgItemList: [{ markItem: undefined }],
      },
      cfgClass: {
        cfgId: undefined,
        classIdList: [],
      },
      rules: {
        behaviorTitle: [{ required: true, message: "必填", trigger: "blur" }],
      },
    };
  },
  computed: {},

  created() {
    this.getList();
    this.getAllClass();
  },

  methods: {
    /** 分页序号自增 */
    table_index(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },

    /** 查询所有班级 */
    getAllClass() {
      findAllSchoolClass().then((result) => {
        this.classOption = result.data;
      });
    },

    /** 查询参数列表 */
    getList() {
      this.loading = true;
      findCfgPageList(this.queryParams)
        .then((response) => {
          this.dataList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        })
        .catch((res) => {
          this.loading = false;
        });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置查询 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 多选 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增配置 */
    handleAdd() {
      this.cfgDialogLoading = false;
      this.reset(this.behaviorCfgForm);
      this.cfgDialogVisible = true;
      this.title = "新增配置";
      this.isView = false;
    },

    /** 修改配置 */
    handleUpdate(row) {
      this.title = "修改配置";
      this.cfgDialogVisible = true;
      this.cfgDialogLoading = true;
      this.isView = true;
      if(row.status == 0){
        this.isEdit = false;
      }
      this.behaviorCfgForm.id = row.id;
      this.behaviorCfgForm.behaviorTitle = row.behaviorTitle;
      this.behaviorCfgForm.scoreCycle = row.scoreCycle;
      findBehaviorCfgItemByCfgId(row.id).then((resp) => {
        this.behaviorCfgForm.behaviorCfgItemList = resp.data;
        this.cfgDialogLoading = false;
      });
    },

    /** 删除配置 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除"' + row.behaviorTitle + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delCfg(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },

    /** 重置表单 */
    reset() {
      this.behaviorCfgForm = {
        id: undefined,
        behaviorTitle: undefined,
        scoreCycle: undefined,
        behaviorCfgItemList: [{ markItem: undefined }],
      };
      this.resetForm("behaviorCfgForm");
    },

    /** 提交表单 */
    submitForm() {
      this.$refs["behaviorCfgForm"].validate((valid) => {
        if (valid) {
          createOrUpdateCfg(this.behaviorCfgForm).then((resp) => {
            this.$message({ message: "提交成功", type: "success" });
            this.cfgDialogVisible = false;
            this.getList();
          });
        }
      });
    },

    /** 关闭弹窗 */
    handleClose(done) {
      this.cfgDialogVisible = false;
      this.cfgClassDialogVisible = false;
    },

    /** 增加行 */
    addRow() {
      this.behaviorCfgForm.behaviorCfgItemList.push({ markItem: undefined });
    },

    /** 删除行 */
    delRow(index, row) {
      var that = this;
      var behaviorCfgItemList = that.behaviorCfgForm.behaviorCfgItemList;
      for (var i = 0; i < behaviorCfgItemList.length; i++) {
        if (row.markItem == behaviorCfgItemList[i].markItem) {
          that.behaviorCfgForm.behaviorCfgItemList.splice(i, 1);
        }
      }
    },

    /** 数据初始化 */
    beforeCreateCfgClass(row) {
      this.cfgClassDialogVisible = true;
      this.cfgClassDialogLoading = true;
      this.transferMonitor = true;
      this.cfgClass.cfgId = row.id;
      this.cfgClass.classIdList = [];
      findCfgClassByCfgId(row.id).then((res) => {
        for (var i = 0; i < res.data.length; i++) {
          this.cfgClass.classIdList.push(res.data[i].classId);
        }
        this.cfgClassDialogLoading = false;
      });
    },

    /** 监听穿梭框是否数据有变化 */
    monitorTransferChange(value, direction, movedKeys) {
      this.transferMonitor = false;
      // this.cfgClass.classIdList = value;
    },

    createCfgClass() {
      if (this.transferMonitor) {
        //穿梭框数据为变化，不发送请求
        this.cfgClassDialogVisible = false;
        this.getList();
      } else {
        createOrUpdateCfgClassBatch(this.cfgClass).then((reslut) => {
          this.$message({ message: "提交成功", type: "success" });
          this.cfgClassDialogVisible = false;
          this.getList();
        });
      }
    },
  },
};
</script>

<style>
</style>